package com.ktjiaoyu.ktmall.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;
import com.ktjiaoyu.ktmall.service.impl.CategoryServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author xm
 * @date 2025/9/12
 * @Dome
 */
@WebServlet(name = "CategoryServlet", urlPatterns = "/api/category/*")
public class CategoryServlet extends HttpServlet {
    private final CategoryService categoryService = new CategoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();
        R result;

       if("/tree".equals(path)){
           List<Category> tree = categoryService.findTree();
           result = R.ok(tree);
       }else {
           List<Category> list = categoryService.findAll();
           result = R.ok(list);
       }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String pathInfo = req.getPathInfo();
        Long id = null;
        if (pathInfo != null && pathInfo.startsWith("/delete/")) {
            String idStr = pathInfo.substring("/delete/".length());
            id = Long.parseLong(idStr);
        }
        boolean success = id != null && categoryService.removeById(id);
        R result = success ? R.ok() : R.fail();
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理新增逻辑
        handleSaveOrUpdate(req, resp, false);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理更新逻辑
        handleSaveOrUpdate(req, resp, true);
    }

    private void handleSaveOrUpdate(HttpServletRequest req, HttpServletResponse resp, boolean isUpdate) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        try {
            Category category = JSON.parseObject(sb.toString(), Category.class);

            // 验证必要字段
            if (category.getName() == null || category.getName().trim().isEmpty()) {
                R result = R.fail("分类名称不能为空");
                writeResponse(resp, result);
                return;
            }

            boolean success;
            if (isUpdate) {
                if (category.getId() == null) {
                    R result = R.fail("更新时ID不能为空");
                    writeResponse(resp, result);
                    return;
                }
                success = categoryService.update(category) > 0;
            } else {
                success = categoryService.insert(category) > 0;
            }

            R result = success ? R.ok() : R.fail("操作失败");
            writeResponse(resp, result);
        } catch (Exception e) {
            e.printStackTrace();
            R result = R.fail("服务器异常：" + e.getMessage());
            writeResponse(resp, result);
        }
    }

    private void writeResponse(HttpServletResponse resp, R result) throws IOException {
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}
